//new Promise封装起来使用，避免代码多次重复
import {useAppStore} from "@/stores/app";
// @ts-ignore
import {QQMapWX} from '../static/qqmap-wx-jssdk/qqmap-wx-jssdk.js'
import {any} from "weapp-tailwindcss-webpack-plugin/types/extractors/regex"; //引入下载的js
import {jsonp} from 'vue-jsonp'


const key = 'W4FBZ-KQZCV-PH5PY-56LLH-EWCF3-CKFBQ'
const referer = useAppStore().getWebsiteConfig.shop_name || '';
 
// 腾讯地图经纬度转中文地址
export function getAddress(lat: any, lng: any) {
    return new Promise((resove, reject) => {
        // #ifdef MP-WEIXIN
        const qqmapsdk = new QQMapWX({
            key,
        })
        qqmapsdk.reverseGeocoder({
            location: {
                latitude: lat,
                longitude: lng,
            },
            success: (res: any) => {
                uni.setStorageSync('location',res.result)
                resove(res.result)
            },
            fail: (e: any) => {
                uni.showToast({
                    title: '获取位置失败：' + e,
                    icon: 'none'
                })
                reject(e)
            },
        })
        // #endif

        // #ifdef H5
        const location = lat + ',' + lng
        jsonp(
            // 'https://apis.map.qq.com/ws/geocoder/v1',
            'http://xqjy.ybzjkj.com/geocoder/v1',
            {
                key,
                location,
                output: "jsonp"
            },
        ).then((res: any) => {
            uni.setStorageSync('location',res.result)
            resove(res.result)
        }).catch((err: any) => {
            uni.showToast({
                title: '获取位置失败：' + err,
                icon: 'none'
            })
            reject(err)
        })

        // #endif
    })
}

export function chooseAddress(lat: any, lng: any, category: any = '') {
    const location = JSON.stringify({
        lat, lng
    })
    uni.navigateTo({
        url: 'plugin://chooseLocation/index?key=' + key + '&referer=' + referer + '&location=' + location + '&category=' + category
    });
}